package com.gccloud.design.service.impl;

import com.gccloud.design.dao.SdApiParmaScriptDao;
import com.gccloud.design.dto.SdApiParamDto;
import com.gccloud.design.entity.SdApiRelaParamEntity;
import com.gccloud.design.entity.SdApiScriptTemplateEntity;
import com.gccloud.design.service.SdApiParamScriptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author wu.yumin
 * @version 1.0.0
 * @Description
 * @date 2021/10/20 10:34
 */
@Service
@Slf4j
public class SdApiParamScriptServiceImpl implements SdApiParamScriptService {
    @Resource
    private SdApiParmaScriptDao sdApiParmaScriptDao;

    @Override
    public SdApiParamDto queryConfig(String apiId) {
        SdApiParamDto dto = new SdApiParamDto();
        List<SdApiRelaParamEntity> list = sdApiParmaScriptDao.queryParamsByApiId(apiId);
        SdApiScriptTemplateEntity scriptTemplateEntity = sdApiParmaScriptDao.queryScriptTemplateByApiId(apiId);
        dto.setScript(scriptTemplateEntity);
        dto.setParams(list);
        return dto;
    }

    @Override
    public boolean saveOrUpdateConfig(SdApiParamDto dto) {

        List<SdApiRelaParamEntity> params = dto.getParams();
        SdApiScriptTemplateEntity script = dto.getScript();
        try {
            sdApiParmaScriptDao.deleteParamsByApiId(String.valueOf(script.getApiId()));
            for (SdApiRelaParamEntity entity:params) {
                sdApiParmaScriptDao.insertParams(entity);
            }
            if (script.getId() == 0) {
                sdApiParmaScriptDao.insertScriptTemplate(script);
            } else {
                sdApiParmaScriptDao.updateScriptTemplate(script);
            }
            return true;
        }catch (Exception e){
            log.error("更新api参数模版失败",e);
            return false;
        }


    }
}
